﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using System.Text;
using System.Data;
using Maticsoft.Common;

namespace Admin.Finance.SubInvoice
{
    public partial class Add : System.Web.UI.Page
    {
        private ChinaSoft.BLL.BLL_tb_MidSoft_FinanceSubInvoice bll = new ChinaSoft.BLL.BLL_tb_MidSoft_FinanceSubInvoice();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (Request.Params["ContractId"] != null && Request.Params["ContractId"].Trim() != "")
                {
                    BindInfo(ChinaSoft.Common.Input.SetInt(Request.Params["ContractId"]));
                    BindData();
                }
                if (Request.Params["id"] != null && Request.Params["id"].Trim() != "")
                {
                    BindEditInfo(ChinaSoft.Common.Input.SetInt(Request.Params["id"]));
                }
            }
        }
        private void BindEditInfo(int id)
        {
            ChinaSoft.Model.Model_tb_MidSoft_FinanceSubInvoice model = bll.GetModel(id);
            txtCreateUser.Text = model.CreateUser;
            txtInvoiceNumber.Text = model.InvoiceNumber;
            txtCustomer.Text = model.Customer;
            txtReceiveMan.Text = model.ReceiveMan;
            ddlDeparMent.SelectedValue = model.CreateDepartment;
            txtInvoiceMoney.Value = model.InvoiceMoney.ToString();
            txtInvoiceDate.Value = Convert.ToDateTime(model.InvoiceDate).ToShortDateString();
        }

        private void BindInfo(int contractId)
        {
            ChinaSoft.BLL.Common.Bind bllBind = new ChinaSoft.BLL.Common.Bind();
            DataSet ds = bllBind.GetDataSet("ProjectInfoId,ProjectNumber,ProjectName,ContractId,ContractNumber,ContractName,ContractMoney", "V_ContractList", "ContractId=" + contractId);
            if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                DataRow dr = ds.Tables[0].Rows[0];
                lblProjectNumber.Text = dr["ProjectNumber"].ToString();
                lblProjectName.Text = dr["ProjectName"].ToString();
                lblContractName.Text = dr["ContractName"].ToString();
                lblContractNumber.Text = dr["ContractNumber"].ToString();
                hiddenContractMoney.Value = lblContractMoney.Text = dr["ContractMoney"].ToString();
                hiddenProjectId.Value = dr["ProjectInfoId"].ToString();
                hiddenContractId.Value = dr["ContractId"].ToString();
            }
            ds = bllBind.GetDataSet("sum(InvoiceMoney) as AllMainInvoiceMoney", "tb_MidSoft_FinanceSubInvoice", "ContractId=" + contractId);
            decimal allInvoiceMoney = Convert.ToDecimal(ds.Tables[0].Rows[0]["AllMainInvoiceMoney"]);
            if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                lblMaxMoney.Text = (Convert.ToDecimal(hiddenContractMoney.Value) - allInvoiceMoney).ToString();
            }
        }

        #region gridView
        public void BindData()
        {
            #region
            //if (!Context.User.Identity.IsAuthenticated)
            //{
            //    return;
            //}
            //AccountsPrincipal user = new AccountsPrincipal(Context.User.Identity.Name);
            //if (user.HasPermissionID(PermId_Modify))
            //{
            //    gridView.Columns[6].Visible = true;
            //}
            //if (user.HasPermissionID(PermId_Delete))
            //{
            //    gridView.Columns[7].Visible = true;
            //}
            #endregion
            StringBuilder strWhere = new StringBuilder();
            if (Request.Params["ContractId"] != null && Request.Params["ContractId"].Trim() != "")
            {
                strWhere.AppendFormat(" and ContractId=" + Request.Params["ContractId"]);
            }
            if (txtStartNumberSearch.Text.Trim() != ""&&txtEndNumberSearch.Text.Trim()!="")
            {
                strWhere.AppendFormat(" and InvoiceNumber between '{0}' and '{1}'", txtStartNumberSearch.Text.Trim(),txtEndNumberSearch.Text.Trim());
            }
            else if (txtStartNumberSearch.Text.Trim() != "" && txtEndNumberSearch.Text.Trim() == "")
            {
                strWhere.AppendFormat(" and InvoiceNumber>'{0}'",txtStartNumberSearch.Text.Trim());
            }
            else if (txtStartNumberSearch.Text.Trim() == "" && txtEndNumberSearch.Text.Trim() != "")
            {
                strWhere.AppendFormat(" and InvoiceNumber<'{0}'",txtEndNumberSearch.Text.Trim());
            }
            if (txtCustomerSearch.Text.Trim() != "")
            {
                strWhere.AppendFormat(" and Customer like '%{0}%'", txtCustomerSearch.Text.Trim());
            }
            try
            {
                //lblCount.Text = (new ChinaSoft.BLL.Common.Pager()).RecordCount("V_ContractList", strWhere.ToString()).ToString();
                ChinaSoft.BLL.Common.Pager.BindGridView(gridView, AspNetPager1, "V_FinaceSubInvoiceList", "SubInvoiceId", "*", strWhere.ToString(), "CreateDate desc", "");
            }
            catch (Exception ex)
            {
                Response.Write("数据库错误：" + ex.Message);
                Response.End();
            }
        }
        protected void AspNetPager1_PageChanged(object sender, EventArgs e)
        {
            BindData();
        }
        protected void gridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            gridView.PageIndex = e.NewPageIndex;
            BindData();
        }
        protected void gridView_OnRowCreated(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.Header)
            {
                e.Row.Cells[0].Text = "<input type=\"checkbox\" id=\"cbSelectAll\" name=\"cbSelectAll\" onclick=\"javascript:checkJs(this.checked);\" />";
            }
        }
        protected void gridView_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                //LinkButton linkbtnDel = (LinkButton)e.Row.FindControl("LinkButton1");
                //linkbtnDel.Attributes.Add("onclick", "return confirm(\"你确认要删除吗\")");

                //object obj1 = DataBinder.Eval(e.Row.DataItem, "Levels");
                //if ((obj1 != null) && ((obj1.ToString() != "")))
                //{
                //    e.Row.Cells[1].Text = obj1.ToString();
                //}

            }
        }
        protected void gridView_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            //#warning 代码生成警告：请检查确认真实主键的名称和类型是否正确
            int ID = (int)gridView.DataKeys[e.RowIndex].Value;
            if (ID.ToString().Trim().Length == 0)
                return;
            ///对数据做删除
            bll.Delete(ID);
            BindData();
            //gridView.OnBind();
        }
        private string GetSelIDlist()
        {
            string idlist = "";
            bool BxsChkd = false;
            for (int i = 0; i < gridView.Rows.Count; i++)
            {
                CheckBox ChkBxItem = (CheckBox)gridView.Rows[i].FindControl("checkboxname");
                if (ChkBxItem != null && ChkBxItem.Checked)
                {
                    BxsChkd = true;
                    //#warning 代码生成警告：请检查确认Cells的列索引是否正确
                    if (gridView.DataKeys[i].Value != null)
                    {
                        idlist += gridView.DataKeys[i].Value.ToString() + ",";
                    }
                }
            }
            if (BxsChkd)
            {
                idlist = idlist.Substring(0, idlist.LastIndexOf(","));
            }
            return idlist;
        }
        #endregion

        protected void btnSearch_Click(object sender, ImageClickEventArgs e)
        {
            BindData();
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            string strErr = "";
            if (this.txtCustomer.Text.Trim().Length == 0)
            {
                strErr += "客户单位不能为空！\\n";
            }
            if (this.txtReceiveMan.Text.Trim().Length == 0)
            {
                strErr += "接收人不能为空！\\n";
            }
            if (!PageValidate.IsAllNumber(txtInvoiceMoney.Value))
            {
                strErr += "开票金额格式错误！\\n";
            }

            if (strErr != "")
            {
                MessageBox.Show(this, strErr);
                return;
            }
            int ProjectInfoId = int.Parse(this.hiddenProjectId.Value);
            int ContractId = int.Parse(this.hiddenContractId.Value);
            string Customer = this.txtCustomer.Text;
            string InvoiceNumber = this.txtInvoiceNumber.Text;
            DateTime InvoiceDate = DateTime.Parse(this.txtInvoiceDate.Value);
            string ReceiveMan = this.txtReceiveMan.Text;
            decimal InvoiceMoney = decimal.Parse(this.txtInvoiceMoney.Value);
            string CreateUser = txtCreateUser.Text.Trim();
            string CreateDepartment = this.ddlDeparMent.Text;
            DateTime CreateDate = DateTime.Now;
            int CreateUserId = ChinaSoft.Common.Input.SetInt(Session["currentUserID"]);
            if (Request.Params["id"] != null && Request.Params["id"].Trim() != "")//编辑
            {
                ChinaSoft.Model.Model_tb_MidSoft_FinanceSubInvoice model = bll.GetModel(ChinaSoft.Common.Input.SetInt(Request.Params["id"]));
                model.CreateUser = txtCreateUser.Text;
                model.InvoiceNumber = txtInvoiceNumber.Text;
                model.Customer = txtCustomer.Text;
                model.ReceiveMan = txtReceiveMan.Text;
                model.CreateDepartment = ddlDeparMent.SelectedValue;
                model.InvoiceMoney = Convert.ToDecimal(txtInvoiceMoney.Value);
                model.InvoiceDate = Convert.ToDateTime(txtInvoiceDate.Value);

                bll.Update(model);
            }
            else
            {
                ChinaSoft.Model.Model_tb_MidSoft_FinanceSubInvoice model = new ChinaSoft.Model.Model_tb_MidSoft_FinanceSubInvoice();
                model.ProjectInfoId = ProjectInfoId;
                model.ContractId = ContractId;
                model.Customer = Customer;
                model.InvoiceNumber = InvoiceNumber;
                model.InvoiceDate = InvoiceDate;
                model.ReceiveMan = ReceiveMan;
                model.InvoiceMoney = InvoiceMoney;
                model.CreateUser = CreateUser;
                model.CreateDepartment = CreateDepartment;
                model.CreateDate = CreateDate;
                model.CreateUserId = CreateUserId;

                bll.Add(model);
            }
            #region 检查合同状态
            ChinaSoft.BLL.BLL_tb_MidSoft_Contract bllContract = new ChinaSoft.BLL.BLL_tb_MidSoft_Contract();
            ChinaSoft.Model.Model_tb_MidSoft_Contract modelContract = new ChinaSoft.Model.Model_tb_MidSoft_Contract();
            if (Convert.ToDecimal(txtInvoiceMoney.Value) == Convert.ToDecimal(lblMaxMoney.Text)) //用户输入的钱数和最大值相等，则更改合同状态为1，已付款完成
            {
                modelContract = bllContract.GetModel(ContractId);
                modelContract.PayState = "1";
                if (string.IsNullOrEmpty(modelContract.FileFolder))
                {
                    modelContract.FileFolder = "";
                    modelContract.FileName = "";
                    modelContract.FileSaveName = "";
                }
                bllContract.Update(modelContract);
            }
            else if (Convert.ToDecimal(txtInvoiceMoney.Value) < Convert.ToDecimal(lblMaxMoney.Text))//用户输入的钱数小于最大值，更改合同状态为0，付款未完成
            {
                modelContract = bllContract.GetModel(ContractId);
                modelContract.PayState = "0";
                if (string.IsNullOrEmpty(modelContract.FileFolder))
                {
                    modelContract.FileFolder = "";
                    modelContract.FileName = "";
                    modelContract.FileSaveName = "";
                }
                bllContract.Update(modelContract);
            }
            #endregion
            Response.Redirect("/Finance/SubInvoice/Add.aspx?ContractId=" + ContractId);
            //Response.Write("<script>alert('成功！');top.window.parent.frames.item('workspace').location.reload();window.parent.$('#DivSysiframe').dialog(\"close\");</script>");
        }

    }
}